package com.wanghua.mall.ware.service.impl;

import com.wanghua.common.utils.R;
import com.wanghua.mall.ware.openfeign.UserClient;
import com.wanghua.mall.ware.vo.FareVo;
import com.wanghua.mall.ware.vo.UserReceiveAddressVo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghua.common.utils.PageUtils;
import com.wanghua.common.utils.Query;

import com.wanghua.mall.ware.dao.WareInfoDao;
import com.wanghua.mall.ware.entity.WareInfoEntity;
import com.wanghua.mall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Resource
    private UserClient userClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            queryWrapper.like("name", key).or().like("address", key);
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据地址id获取运费
     *
     * @param addressId
     * @return
     */
    @Override
    public FareVo getFare(Long addressId) {
        R r = userClient.getAddressInfo(addressId);
        UserReceiveAddressVo userReceiveAddressVo = (UserReceiveAddressVo) r.get("userReceiveAddress");
        if (userReceiveAddressVo != null) {
            String phone = userReceiveAddressVo.getPhone();
            if (phone != null) {
                //TODO 待完善更详细的运费信息,这里采用手机号后四位作为运费
                String fare = phone.substring(8, 12);

                return new FareVo(userReceiveAddressVo, new BigDecimal(fare));
            }
        }
        return new FareVo(userReceiveAddressVo, new BigDecimal(9999));
    }

}